package kr.yoon.practice.db.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class DBProperties {
	public static void saveProperties(String propertiesFiles, String...values){
		BufferedOutputStream bos = null;
		Properties prop = null;
		
		try {
			bos = new BufferedOutputStream(new FileOutputStream(propertiesFiles));
			prop = new Properties();
			
			prop.setProperty("DRIVER", values[0]);
			prop.setProperty("URL", values[1]);
			prop.setProperty("USER", values[2]);
			prop.setProperty("PASSWORD", values[3]);
			
			prop.storeToXML(bos, "DataBase Connection XML Property File");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bos != null){ //null과 같지 않다면..
				
				try {
					bos.close();
					bos = null;
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
			
		}
	} // end of saveProperties Method
	
	public static Properties loadProperties(String propertiesFiles){
		BufferedInputStream bis = null;
		Properties prop = null;
		
		try {
			bis = new BufferedInputStream(new FileInputStream(propertiesFiles));
			prop = new Properties();
			prop.loadFromXML(bis); //bis를 xml파일로 발행..
		} catch (FileNotFoundException e) {
			System.err.print("파일이 존재하지 않음");
		} catch (InvalidPropertiesFormatException e) {
			System.err.print("유효하지 않는 파일");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bis != null){
				try {
					bis.close();
					bis = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		return prop;
	} // end of loadProperties Method
	
	public static void prnProperties(Properties prop){
		Set<Entry<Object, Object>> setmap = prop.entrySet();
		
		for(Entry<Object, Object> propty : setmap){
			System.out.printf("%s : %s\n", propty.getKey(), propty.getValue());
		}
	}
}
